package com.kehutong.house.admin;

import com.kehutong.common.ExcelUtil;
import com.kehutong.common.excel.tool.ExcelTool;
import com.kehutong.common.util.ListUtils;
import com.kehutong.house.dto.SupplierDto;
import com.kehutong.house.entity.Supplier;
import com.kehutong.house.entity.SupplierGoods;
import com.kehutong.house.service.SupplierService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

import java.io.File;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO 供应商管理
 *
 * @author zwp
 * @version 1.0
 * @date 2021/6/29 16:41
 */
@MvcAction
@ReqMapping("/admin/basic/supplier")
public class SupplierController {
    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private SupplierService supplierService;

    @Inject
    ExcelTool excelTool;

    @ReqMapping("/list")
    public Page<Supplier> list(JSONObject jsonObject) throws Exception {
        FindPage<Supplier> findPage = jdbcSession.findPage(Supplier.class);
        findPage.eq("deleted",false);
        String name = jsonObject.getString("name");
        String goodsId = jsonObject.getString("goodsId");
        if(jsonObject.containsKey("status")&&Objects.nonEmpty(jsonObject.getString("status"))){
            boolean status = jsonObject.getBoolean("status");
            findPage.eq("status",status);
        }
        if(Objects.nonEmpty(name)){
            findPage.like("name",name);
        }
        if(Objects.nonEmpty(goodsId)){
            findPage.like("goodsId",goodsId);
        }
        findPage.page(jsonObject);
        Page<Supplier> page = findPage.exe();
        Map<String,String>supplierGoodsMap=getSupplierGoodsMap();
        page.getList().forEach(item -> {
            StringBuffer sb = new StringBuffer();
            List<String> goodsIds =new ArrayList<>();
            item.getGoodsId().stream().forEach(str->{
                if(supplierGoodsMap.get(str)!=null){
                    sb.append(supplierGoodsMap.get(str)).append(",");
                    goodsIds.add(str);
                }
            });
            if(sb.length()>0 ){
                sb.setLength(sb.length()-1);
                item.setGoodsName(sb.toString());
                item.setGoodsId(goodsIds);
            }

        });
        return page;
    }
    @Bean(newInstance=true, copy=true)
    @ReqMapping("/save")
    public Object save(Supplier supplier)throws Exception  {
        System.out.println("入参"+supplier);
        jdbcSession.insert(supplier);
        return Result.success(supplier);
    }
    @Bean(newInstance=true, copy=true)
    @ReqMapping("/update")
    public Object update(Supplier supplier)throws Exception  {
        jdbcSession.updateById(supplier);
        return Result.success(supplier);
    }
    @ReqMapping("/delete")
    public Object delete(Supplier supplier) throws Exception {
        if (Objects.nonNull(supplier)) {
            supplier.setDeleted(true);
            jdbcSession.updateById(supplier);
        }
        return Result.success();
    }
    @ReqMapping("/get")
    public Object get(String id) throws Exception {
        Supplier supplier=jdbcSession.findById(Supplier.class,id);
        if(supplier!=null && supplier.getGoodsId().size()>0){
            Map<String,String>supplierGoodsMap=getSupplierGoodsMap();
            StringBuffer sb = new StringBuffer();
            supplier.getGoodsId().stream().forEach(str->{
                if(supplierGoodsMap.get(str)!=null){
                    sb.append(supplierGoodsMap.get(str)).append(",");
                }
            });
            if(sb.length()>0){
                sb.setLength(sb.length()-1);
                supplier.setGoodsName(sb.toString());
            }
        }
        return supplier;
    }
    @ReqMapping("/exportSupplierData")
    public Object exportSupplierData(JSONObject jsonObject) throws Exception {
        jsonObject.put("pageNo", 1);
        jsonObject.put("pageSize", Short.MAX_VALUE);
        Page<Supplier> page = list(jsonObject);
        File dataFile = exportFriendDataFile(page.getList());
        return com.kehutong.common.errcode.Result.download(dataFile);
    }
    private File exportFriendDataFile(List<Supplier> supplierList) throws Exception {
        Workbook wb = exportSupplierWorkBook(supplierList);
        return ExcelUtil.writeXlsFile(wb, "供应商列表", ".xls");
    }
    private Workbook exportSupplierWorkBook(List<Supplier> supplierList) {
        Map<String,String>supplierGoodsMap=getSupplierGoodsMap();
        supplierList.forEach(item -> {
            StringBuilder stringBuilder=new StringBuilder();
            item.getGoodsId().forEach(goodsId->{
                stringBuilder.append(supplierGoodsMap.get(goodsId));
                stringBuilder.append(",");
            });
            stringBuilder.setLength(stringBuilder.length()-1);
            item.setGoodsName(stringBuilder.toString());
        });
        // 生成模板文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建工具
        CreationHelper helper = wb.getCreationHelper();
        //单元格样式类
        CellStyle dateCellStyle = wb.createCellStyle();
        //设置单元格格式
        dateCellStyle.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

        Sheet sheet = wb.createSheet();
        Row headerRow = sheet.createRow(0);
        int headerCellNum = 0;
        String[] chargeUserInstrument = {"供应商名称", "供应物品", "联系人", "手机号码", "状态"};
        for (String s : chargeUserInstrument) {
            Cell cell = headerRow.createCell(headerCellNum++);
            cell.setCellValue(s);
        }

        int cellNum = 0;
        for (int i = 0; i < supplierList.size(); i++) {
            Supplier supplier = supplierList.get(i);
            Row row = sheet.createRow(i + 1);
            cellNum = 0;
            row.createCell(cellNum++).setCellValue(supplier.getName());
            row.createCell(cellNum++).setCellValue(supplier.getGoodsName());
            row.createCell(cellNum++).setCellValue(supplier.getLiaisonMan());
            row.createCell(cellNum++).setCellValue(supplier.getPhone());
            row.createCell(cellNum++).setCellValue(supplier.isStatus()?"启用":"停用");
            Cell tmpCell = row.createCell(cellNum++);
            tmpCell.setCellStyle(dateCellStyle);
        }

        // 自动列宽
        for (int i = 0; i < cellNum; i++) {
            if (i == 0) {
                // id列不调整
                continue;
            }
            // 自动列宽
            ExcelUtil.autoSizeColumn(sheet, i);
        }
        return wb;
    }

    /**
     * 获取供应商物品map
     * @return supplierGoodsMap
     */
    public Map<String,String> getSupplierGoodsMap(){
        //查询供应物品
        List<SupplierGoods>supplierGoodsList=jdbcSession.findArray(SupplierGoods.class)
                .eq("deleted", false)
                .eq("status",true)
                .exe();
        Map<String,String>supplierGoodsMap=supplierGoodsList.stream().collect(Collectors.toMap(SupplierGoods::getId,SupplierGoods::getName));
        return supplierGoodsMap;
    }
    public Map<String,String> getSupplierGoodsMapKey(){
        //查询供应物品
        List<SupplierGoods>supplierGoodsList=jdbcSession.findArray(SupplierGoods.class)
                .eq("deleted", false)
                .eq("status",true)
                .exe();
        Map<String,String>supplierGoodsMap=supplierGoodsList.stream().collect(Collectors.toMap(SupplierGoods::getName,SupplierGoods::getId));
        return supplierGoodsMap;
    }
    @ReqMapping("/checkFileSupplier")
    public Object checkFileSupplier(JSONObject jsonObject) throws Exception {
        return supplierService.checkFile(jsonObject);
    }
    @ReqMapping("/readFile")
    public Object readFile(JSONObject jsonObject) throws Exception {
        List<SupplierDto> list = excelTool.excelImport(jsonObject, SupplierDto.class);
        List<Supplier> supplierList = ListUtils.copyBeanList(list, ()->Pool.newInstance(Supplier.class));
        //遍历把供应物品名称改成供应物品ID
        Map<String,String>supplierGoodsMapkey=getSupplierGoodsMapKey();
        supplierList.forEach(str -> {
            List<String> childTb=new ArrayList();
            List<String> goodsId=str.getGoodsId();
            for(String src : goodsId) {
                childTb.add(supplierGoodsMapkey.get(src));
            }
            str.setGoodsId(childTb);

        });
        //批量插入
        jdbcSession.insert(supplierList);
        return Result.success();
    }

}
